#include "common.h"

volatile struct can_reg *can = (volatile struct can_reg *)0x40006400;

void init_can_pin(void)
{
    afio->MAPR &= ~(3 << 13);
    SET_BITS(gpioa->CRH, 13, 12, 0);
    SET_BITS(gpioa->CRH, 15, 14, 2);
    gpioa->ODR |= (1 << 11);
    SET_BITS(gpioa->CRH, 17, 16, 3);
    SET_BITS(gpioa->CRH, 19, 18, 2);
};

void init_can1(void)
{
    can = (volatile struct can_reg *)0x40006400;
    union can_ext_flag_all can_ext_flag;
    init_can_pin();
    rcc->APB1ENR |= (1 << 25);
    can->MCR |= (1 << 15);
    while (can->MCR & (1 << 15))
        ;
    can->MCR |= (1 << 0);
    while (!(can->MSR & (1 << 0)))
        ;
    can->MCR |= (1 << 6);

    can->BTR = (15 << 0) | (4 << 16) | (2 << 20) | (2 << 24);

    can->IER |= (1 << 1);  // 接收FIFO 0挂起中断使能

    can->FMR |= (1 << 0);

    can->FM1R &= ~(1 << 0);   // 屏蔽位模式
    can->FS1R |= (1 << 0);    // 单个32位
    can->FFA1R &= ~(1 << 0);  // 关联到FIFO_0

    can_ext_flag.all            = 0;
    can_ext_flag.part.src       = 2;
    can_ext_flag.part.dst       = adaptor_parm.can_id;
    can_ext_flag.part.cmd       = 300;
    can_ext_flag.part.rtr       = 0;
    can_ext_flag.part.ide       = 1;
    can->sFilterRegister[0].FR1 = can_ext_flag.all;

    can_ext_flag.all            = 0;
    can_ext_flag.part.src       = 0xff;
    can_ext_flag.part.dst       = 0;
    can_ext_flag.part.cmd       = 0xfff;
    can_ext_flag.part.rtr       = 1;
    can_ext_flag.part.ide       = 1;
    can->sFilterRegister[0].FR2 = can_ext_flag.all;

    can->FA1R |= (1 << 0);  // 激活过滤器

    can->FMR &= ~(1 << 0);  // 过滤器正常模式

    nvic->ISER[0] = (1 << 20);

    can->MCR &= ~(1 << 0);
    while (can->MSR & (1 << 0))
        ;
    can->MCR &= ~(1 << 1);
}
